var _CONFIG = {
    TYPE:'Web',
    JQXGRID: '#jqx_grid_view',
    tBINDING_URI: base_url + 'so/menu/binding/',
    BINDING_URI: base_url + 'so/menu/databinding/',
    EDITPANEL_URI:base_url + 'so/menu/editpanel/',
    COMMIT_URI:base_url + 'so/category/commit/',
    DELETE_URI:base_url + 'so/category/delete/'
};
var _SO = (function() {
    var oTable;
    var that = this;
    var datafields = [
        {name: 'Id', type: 'int'},
        {name: 'Thumb'},
        {name: 'Title'},
        {name: 'Display'},
        {name: 'ParentTitle'},
        {name: 'Parent', type: 'int'},
        {name: 'Type'},{name: 'Level', type: 'int'},
        {name: 'Position',type: 'int'},
        {name: 'Active',type: 'bool'},
        {name: 'Insert', type: 'date'},
        {name: 'Update', type: 'date'},
    ];
    var source,dataAdapter;
    return {
        onCommit: function(Params, Id,callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
        creategrid:function(){
            
            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI+_CONFIG.TYPE,
                hierarchy:
                {
                    keyDataField: { name: 'Id' },
                    parentDataField: { name: 'Parent' }
                },
                id:'Id',
                root: 'rows',
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
                {
                    text: '', dataField: 'Id', width: 60, filterable: false, sortable: false,editable: false,
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        var str = "";
                        if (value && value > 0) {
                            try {
                                //value = $.parseJSON(value);
                                str += "\
                                    <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_SO.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                                ";
                                str += "\
                                    <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_SO.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                                ";
                            } catch (e) {
                            }
                        }

                        return str;
                    }
                },
                {
                    text: 'Menu'       , dataField: 'Title',
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                        var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                        str+='<span style="padding-left:'+(dataRow.Level*16)+'px;">'+dataRow.Display+'</span>';
                        str+='</div>';
                        return str;
                    }
                },
                {
                    text: 'Menu Cha'    , dataField: 'Parent',columntype: 'template',
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                        var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                        var display=value;
                        display=dataRow.ParentTitle;
                        str+=display;
                        str+='</div>';
                        return str;
                    },
                    createeditor: function(row, cellvalue, editor, cellText, width, height) {
                        // construct the editor. 
                        editor.jqxDropDownList({
                            //checkboxes: true,
                            source: dataAdapter.records, displayMember: "Display", valueMember: "Id",
                            width: width, height: height, theme: theme,
//                            selectionRenderer: function() {
//                                return "Please Choose:";
//                            }
                        });
                        editor.jqxDropDownList('insertAt',{label:0,value:0},0);
                        editor.jqxDropDownList('getItem',0).label='Root';
                    },
                    initeditor: function(row, cellvalue, editor, celltext, pressedkey) {
                        try{
                            editor.jqxDropDownList('clearSelection');
                            var items = editor.jqxDropDownList('getItems');
                            for (var i = 0; i < items.length; i++) {
                                editor.jqxDropDownList('enableItem',items[i]);
                                if (items[i].value === cellvalue) {
                                    editor.jqxDropDownList('selectItem', items[i]);
                                    //break;
                                } 
                            }
                            var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                            var mylevel=-1;
                            for (var i = 0; i < items.length; i++) {
                                if(mylevel>=0){
                                    if(items[i].originalItem.Level>mylevel){
                                        editor.jqxDropDownList('disableItem',items[i]);
                                    }else{
                                        mylevel=-1; 
                                    }
                                }
                                if(items[i].value===dataRow.Id){
                                    mylevel=items[i].originalItem.Level;
                                    editor.jqxDropDownList('disableItem',items[i]);
                                }
                            }
                        }catch(e){$.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});}
                    },
                    geteditorvalue: function(row, cellvalue, editor) {
                        // return the editor's value.
                        return editor.val();
                    }
                },
                {
                    text: 'Thứ tự'       , dataField: 'Position'    ,
                    width: 80, cellsalign: 'right', 
                    filterable: false, sortable: false,editable: true,
                    columntype: 'numberinput', filtertype: 'number',
                    validation:function (cell, value) {
                        if (value < 0 || value > 99) {
                            return { result: false, message: "Position should be in the 0-99 interval." };
                        }
                        return true;
                    }
                },    
                {
                    text: 'Trạng thái'    , dataField: 'Active' , cellsalign: 'center',
                    width: 80, columntype: 'checkbox', threestatecheckbox: false,
                    filterable: false, sortable: false,editable: true
                },
                {
                    text: 'Created'        , dataField: 'Insert'      , width: 120,  cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false,editable: false
                },
                {
                    text: 'Modified'      , dataField: 'Update'    , width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false,editable: false
                }
            ];
            
            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                editable: true,
				handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel=true;
                    }
                },

            }).bind('cellbeginedit', function (event) {
                that.cancel=false;
            }).bind('cellendedit', function (event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if(that.cancel)return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try{
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value!='')
                                _SO.onCommit({Title: _value}, _id);
                            break;
                        case 'Parent':
                            if (_value != _data.Parent)
                                _SO.onCommit({Parent: _value}, _id,function(){
                                    _SO.onRefresh();
                                });
                            break;
                        case 'Position':
                            if (_value != _data.Position)
                                _SO.onCommit({Position: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _SO.onCommit({Active: 'true'}, _id);
                            else
                                _SO.onCommit({Active: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        createtable :   function(){
            $('#data_table').hide();return;
             oTable = $('#data_table').dataTable({
                aaSorting: [],
                aoColumns: [
                    {
                        mData: "Id",sWidth: "58px",//sClass:'',
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            str += '<span class="icon-pencil" title="Edit:'+value+'" style="padding-right:12px" onclick="_SO.onEditItem(' + value + ');"></span>';
                            str += '<span class="icon-trash" title="Delete:'+value+'" style="padding-right:12px" onclick="_SO.onDeleteItem(' + value + ');"></span>';

                            return str;
                        }
                    },
                    {
                        mData: "Thumb",sWidth: "58px",
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            if(value!==undefined && value !==null  && value!=='')
                                str += '<img src="' + value + '" style="height:24px"/>';
                            return str;
                        }
                    },
                    {
                        mData: "Title",
                        mRender: function ( value, type, datarow ) {
                            return datarow.Display===undefined?value:datarow.Display;
                        }
                    },
                    {
                        mData: "Parent",
                        mRender: function ( value, type, datarow ) {
                            return datarow.ParentTitle===undefined?value:datarow.ParentTitle;
                        }
                    },
                    {mData: "Type"},
                    {mData: "Position"},
                    {
                        mData: "Active",sClass:'center',sWidth: "58px",
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            if(value==='true')
                                str+='<input type="checkbox" onclick="_SO.onStatusChange(this,'+datarow.Id+');" checked=1/>';
                            else
                                str+='<input type="checkbox" onclick="_SO.onStatusChange(this,'+datarow.Id+');"/>';
                            return str;
                        }
                    },
                    {mData: "Insert",bSearchable:false},
                    {mData: "Update",bSearchable:false}
                ],
                sServerMethod: "POST",
                iDisplayLength: 50,
                bProcessing: true,
                bServerSide: true,
                bPaginate: false,
                bSortable:false,
                bFilter :false,
                sAjaxSource: _CONFIG.tBINDING_URI+_CONFIG.TYPE,
                bJQueryUI: false,
                bAutoWidth: false,
                sPaginationType: "full_numbers",
                //sDom": '<"datatable-header"fl>t<"datatable-footer"ip>',
                oLanguage: {
                    sSearch: "<span>Filter records:</span> _INPUT_",
                    sLengthMenu: "<span>Show entries:</span> _MENU_",
                    oPaginate: {"sFirst": "First", "sLast": "Last", "sNext": ">", "sPrevious": "<"}
                }
            });
            oTable.fnSetFilteringDelay(2000);
        },
        onInit  :   function(){
            this.createtable();
            this.creategrid();
        },
        onAddItem:function(){
            this.onEditItem(0);
        },
        onEditItem:function(Id){
            if (PENDING)
                return false;
            $('#dialog-edit-panel>.base-dialog-modal').html('<div class="base_loading" style="display: block;height: 60px"></div>');
            bckdialog({
                title:'Menu',
                message:$('#dialog-edit-panel'),
                buttons: [
                    {
                        text    :'Hoàn thành',
                        class   :'base_button base_green base-small-border-radius',
                        click   : function() {
                            _SO.onSave();
                        }
                    },
                    {
                        text    :'Đóng',
                        class   :'base_button base_red base-small-border-radius',
                        click   : function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            backend({
                url         :   _CONFIG.EDITPANEL_URI+_CONFIG.TYPE,
                data        :   {
                    Id  :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        $('#dialog-edit-panel>.base-dialog-modal').html('<span style="color:red">'+rsdata.message+'</span>');
                    }else{
                        $('#dialog-edit-panel>.base-dialog-modal').html(rsdata.htmlreponse);
                        $('#dialog-edit-panel').dialog('close').dialog('open'); 
                        $('#_form_edit_panel select').select2();
                    }
                }
            }).call();
        },
        onSave:function(){
            if( $('#_form_edit_panel').validationEngine('validate') === false)return false;
            var Params=$('#_form_edit_panel').serializeObject();
            $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').show();
            this.onCommit(Params,$('#Id').val(),function(){
                $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').hide();
                _SO.onRefresh();
                _SO.onCancel();
            });
            return false;
        },
        onCancel:function(){
            $('#dialog-edit-panel').dialog('close');
        },
        onDeleteItem:function(Id){
            backend_delete(_CONFIG.DELETE_URI,Id,function(){
                _SO.onRefresh();
            });
        },
        onRefresh:function(){
            //oTable.fnDraw(false);
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
        onFillter:function(v){
            oTable.fnFilter(v, 2);
        },
        onStatusChange:function(that,Id){
            var _status = $(that).is(':checked')?'true':'false';
            new backend({
                url         :   _CONFIG.COMMIT_URI,
                data        :   {
                    Params  :   {
                        Active:_status
                    },
                    Id      :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }
                }
            }).call();
        },
        onChangeSource:function(type){
            _CONFIG.TYPE=type;
            //oTable.fnDestroy();
            //this.createtable();
            source.url= _CONFIG.BINDING_URI+_CONFIG.TYPE;
            dataAdapter.dataBind();
        }
    };
}());